import { getToken, setToken, getUser, setUser, logOut,setAddRess,getAddRess } from "@/utils/auth";
import loginApi from "@/api/login";
import logoutApi from "@/api/logout"
import { Toast } from 'vant';
export default {
    state: {
        token: getToken(),
        username: getUser(),
        address :getAddRess()
    },
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token;
            setToken(token);
        },
        SET_USER(state,username){
            state.username = username;
            setUser(username);
        },
        REMOVE_INF(state){
            logOut();
            state.token="";
            state.username="";
            state.token="";
        },
        SET_ADDRESS(state,addressObj){
            state.address = addressObj;
            setAddRess(addressObj)
        }
    },
    actions: {
        Login(context, { username, password }) {
            return new Promise(async (resolve, reject) => {
                try {
                    let p = await loginApi.login(username, password);
                    if (p.data.flag) {
                        context.commit("SET_TOKEN", p.data.token)
                        context.commit("SET_USER",p.data.data.username);
                        resolve(p.data)
                    }else{
                        Toast.fail("登录失败")
                    }
                } catch (err) {
                    reject(err)
                }
            })
        },
        logOut({commit,state}){
            return new Promise(async (resolve,reject)=>{
                try{
                    let p = await logoutApi.loginOut(state.username);
                    commit("REMOVE_INF")
                    resolve(p.data)
                }catch(err){
                    reject(err)
                }
            })
        },
        checktoken(context){
            return new Promise(async (resolve,reject)=>{
                try{
                    let p = await loginApi.checkToken(context.state.token)
                    resolve(p)
                }catch(err){
                    reject(err)
                }
            })
        },
        setaddress(context,obj){
            return new Promise(async (resolve,reject)=>{
                try{
                    let {username,phonenum,address} = obj;
                    let p = await loginApi.addRess(username,phonenum,address)
                    if(p.data.flag){
                        context.commit('SET_ADDRESS',obj)
                        resolve(p)
                    }
                }catch(err){
                    reject(err)
                }
            })
        },
    }
}